package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//拦截器,需要在启动类上添加@ServletComponentScan进行扫描
//登录之前的请求都不应该拦截比如验证码,登录,前端资源等
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配类
    public static final AntPathMatcher ANT = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        log.info("拦截到请求uri：{}", uri);





//需要放行的请求数组
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //若拦截到的请求属于需要放行的请求,则放行
        boolean check = check(urls, uri);
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        //若用户已登录也放行
        if (request.getSession().getAttribute("employee") != null) {
            filterChain.doFilter(request, response);
        //预先存储用户id,为后续字段自动填充做准备
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(employeeId);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            filterChain.doFilter(request, response);
            //预先存储用户id,为后续字段自动填充做准备
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            return;
        }


        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


    }

    private boolean check(String[] urls, String uri) {
        for (String url : urls) {
            boolean match = ANT.match(url, uri);
            if (match) {
                return true;

            }
        }
        return false;
    }
}
